<template>
<div class="main-canvas" ref="mainCanvas" id="mainCanvas">
    <div class="canvas-tool">
        <el-tooltip effect="dark" :content="item.name" placement="left" v-for="(item, i) in toolList" :key="i">
            <i id="tools" :style="item.check?'color:#2680eb;':''" :class="`iconfont ${item.icon}`" @click="handleToolBtns(i, item)"></i>
        </el-tooltip>
    </div>
    <div class="canvas-btns">
        <span class="c-f-wrap">
            <el-button type="text" class="c-f-w-item" :class="{'disabled':item.disabled}" @click="clickEditbtns(i, item)" :disabled="item.disabled" v-preventReClick="2000" v-for="(item, i) in editBtns" :key="i">
                <i :class="`iconfont ${item.icon}`"></i>{{item.name}}
            </el-button>
        </span>
        <span class="yunxing-status">
            <i v-show="runingStatus.state === 2" class="el-icon-loading"></i>
            <i v-show="runingStatus.state === 3" class="el-icon-check"></i>
            <span>{{expState}}</span>
            <span v-show="runingStatus.state === 2">，{{time}}</span>
        </span>
    </div>
    <jsplumb-container ref="jsplumbContainer" @on-change-select-dom="handleChangeSelectDom" @initTime="handleInitTime" @start-execute="handleStartExecute" @stop-execute="handleStopExecute"></jsplumb-container>
    <dispatch-set v-if="dispatchData.show" :dispatchData="dispatchData" @save="handleDispatch"></dispatch-set>
</div>
</template>

<script>
import JsplumbContainer from './jsplumb'
import DispatchSet from './dispatchSet'
import {
    mapGetters
} from 'vuex'
import moment from 'moment'
export default {
    name: 'MainCanvas',
    components: {
        DispatchSet,
        JsplumbContainer
    },
    data () {
        return {
            timer: null,
            time: '00:00:00',
            dispatchData: {
                show: false,
                title: '调度任务',
                form: {
                    cronObj: {},
                    periodType: 1,
                    schedulTime: '',
                    period: '',
                    moment: '',
                    status: 0,
                    time: [],
                    description: '',
                    scheduleName: '',
                    upstreamSchedules: [],
                    downstreamSchedules: []
                }
            },
            toolList: [{
                    name: '放大',
                    icon: 'icon-fangda'
                },
                {
                    name: '缩小',
                    icon: 'icon-suoxiao'
                },
                {
                    name: '全屏',
                    icon: 'icon-quanping',
                    check: false
                },
                {
                    name: '适应画布',
                    icon: 'icon-shiyinghuabu'
                },
                {
                    name: '实际尺寸',
                    icon: 'icon-shijichicun'
                },
                {
                    name: '框选节点',
                    icon: 'icon-kuangxuanjiedian',
                    check: false
                }
            ],
            editBtns: [
                {
                    name: '运行实验',
                    icon: 'icon-yunhangshiyan-copy'
                },
                {
                    name: '调度设置',
                    icon: 'icon-tiaodushezhi'
                }
            ]
        }
    },
    computed: {
        ...mapGetters({
            projectId: 'common/getProjectId',
            experimentId: 'common/getExperimentId',
            runingStatus: 'common/getRuningStatus',
            currentExpInfo: 'common/getCurrentExpInfo'
        }),
        expState () {
            let status = null
            if (this.runingStatus) {
                switch (this.runingStatus.state) {
                    case 0:
                        status = '草稿'
                        break
                    case 1:
                        status = '准备中'
                        break
                    case 2:
                        status = '运行中'
                        break
                    case 3:
                        status = '运行结束'
                        break
                    default:
                        status = null
                        break
                }
            }
            return status
        }
    },
    watch: {
        runingStatus (val) {
            if (val) {
                let flag = val.state === 2 || val.state === 1
                this.editBtns[0] = {
                    name: flag ? '停止运行' : '运行实验',
                    icon: flag ? 'icon-zantingshiyan' : 'icon-yunhangshiyan-copy'
                }
                this.editBtns[1].disabled = flag
            }
        }
    },
    methods: {
        handleChangeSelectDom (f) {
            this.toolList[5].check = f
        },
        handleDispatch () {
            let { cronObj, periodType, status, time, scheduleName, upstreamSchedules, downstreamSchedules, description } = this.dispatchData.form
            let params = {
                projectId: this.projectId,
                experimentId: this.experimentId,
                cronObj: JSON.stringify(cronObj),
                periodType,
                status,
                description,
                effDate: time[0] && moment(time[0]).format('YYYY-MM-DD HH:mm:ss'),
                endDate: time[1] && moment(time[1]).format('YYYY-MM-DD HH:mm:ss'),
                scheduleName,
                upstreamSchedules,
                downstreamSchedules
            }
            this.$post('/experiment/updateOfflineSchedule', params).then(res => {
                if (res.periodType) {
                    this.$message.success('保存成功')
                    this.dispatchData.show = false
                }
            })
        },
        // 计时器
        getTime (t) {
            this.timer = setInterval(() => {
                t++
                let h = parseInt(t / 3600)
                let m = parseInt((t - h * 3600) / 60)
                let s = t - h * 3600 - m * 60
                if (h < 10) h = `0${h}`
                if (m < 10) m = `0${m}`
                if (s < 10) s = `0${s}`
                this.time = `${h}:${m}:${s}`
            }, 1000)
        },
        handleInitTime (t) {
            this.clearTimer()
            this.getTime(t)
        },
        startOrEnd (name, icon) {
            this.editBtns[0] = { name, icon }
        },
        clearTimer () {
            if (this.timer) {
                window.clearInterval(this.timer)
                this.timer = null
            }
        },
        handleStartExecute () {
            this.clearTimer()
            this.time = '00:00:00'
            this.getTime(0)
            this.startOrEnd('停止运行', 'icon-zantingshiyan')
        },
        handleStopExecute () {
            this.clearTimer()
            this.startOrEnd('运行实验', 'icon-yunhangshiyan-copy')
        },
        // 保存副本时，修改副本名称
        getExpCopyName (str) {
            if (str.includes(' - 副本')) {
                let arr = str.split(' - 副本')
                if (!arr[1]) {
                    str = `${str} (2)`
                } else {
                    str = `${arr[0]} - 副本 (${arr[1][2] - 0 + 1})`
                }
            } else {
                str = `${str} - 副本`
            }
            return str
        },
        // 画布顶部按钮点击事件
        clickEditbtns (n, item) {
            switch (n) {
                case 0:
                    this.$refs.jsplumbContainer[item.name === '运行实验' ? 'execute' : 'stopExecute']()
                    break
                case 1:
                    let params = {
                        projectId: this.projectId,
                        experimentId: this.experimentId
                    }
                    this.$post('/experiment/queryOfflineSchedules', params).then(res => {
                        if (!res.length) {
                            this.dispatchData.form = {
                                cronObj: {},
                                periodType: 1,
                                schedulTime: '',
                                period: '',
                                moment: '',
                                status: 0,
                                time: [],
                                scheduleName: '',
                                description: '',
                                upstreamSchedules: [],
                                downstreamSchedules: []
                            }
                        } else {
                            let data = res.rows[0]
                            let cronObj = JSON.parse(data.cronObj)
                            let period = ''
                            let moment = ''
                            let schedulTime = ''
                            switch (data.periodType) {
                                case 5:
                                    period = cronObj.monthExp
                                    moment = cronObj.dayExp
                                    schedulTime = new Date(`2019/5/5 ${cronObj.hourExp}:${cronObj.minuteExp}:${cronObj.secondExp}`)
                                    break
                                case 3:
                                    period = cronObj.dayExp
                                    schedulTime = new Date(`2019/5/5 ${cronObj.hourExp}:${cronObj.minuteExp}:${cronObj.secondExp}`)
                                    break
                                case 4:
                                    period = 1
                                    moment = cronObj.weekExp
                                    schedulTime = new Date(`2019/5/5 ${cronObj.hourExp}:${cronObj.minuteExp}:${cronObj.secondExp}`)
                                    break
                                case 2:
                                    period = cronObj.hourExp
                                    schedulTime = new Date(`2019/5/5 ${cronObj.hourExp}:${cronObj.minuteExp}:${cronObj.secondExp}`)
                                    break
                                case 1:
                                    period = cronObj.minuteExp
                                    schedulTime = new Date(`2019/5/5 0:${cronObj.minuteExp}:${cronObj.secondExp}`)
                                    break
                            }
                            this.dispatchData.form = {
                                periodType: data.periodType,
                                schedulTime,
                                period,
                                moment: +moment,
                                cronObj,
                                status: data.status,
                                time: [new Date(data.effDate), new Date(data.endDate)],
                                scheduleName: data.scheduleName,
                                description: data.description,
                                upstreamSchedules: data.upstreamSchedules,
                                downstreamSchedules: data.downstreamSchedules
                            }
                        }
                        this.dispatchData.show = true
                    })
            }
        },
        // 工具栏里各个按钮点击事件
        handleToolBtns (n, item) {
            let node = this.$refs.jsplumbContainer
            switch (n) {
                case 0: // 放大
                    node.getZoom('zoomIn')
                    break
                case 1: // 缩小
                    node.getZoom('zoomOut')
                    break
                case 2: // 全屏
                    item.check = !item.check
                    this.toolList[5].check = false
                    this.$emit('fullScreen')
                    break
                case 3: // 适应画布
                    node.fitCanvas()
                    break
                case 4: // 实际尺寸
                    node.getZoom('restore')
                    break
                case 5: // 框选节点
                    item.check = !item.check
                    node.selectDom()
                    break
            }
        }
    }
}
</script>

<style lang="less">
.main-canvas {
    position: relative;
    width: 100%;
    height: 100%;

    .canvas-status {
        display: flex;
        position: absolute;
        right: 10px;
        top: 0;
        z-index: 1;
        font-size: 12px;
        color: #2c3e50;

        .yunxing-status span {
            padding-left: 5px;
        }

        span {
            display: flex;
            align-items: center;
            justify-content: center;
        }

        i {
            font-size: 18px;
            margin-left: 5px;
        }
    }

    .canvas-btns {
        background: #ffffff;
        position: absolute;
        top: -10px;
        left: -10px;
        right: -10px;
        z-index: 1;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 12px;
        .yunxing-status {
            padding-right: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            span {
                padding-left: 5px;
            }
        }

        i {
            font-size: 18px;
            margin-left: 5px;
        }

        .c-f-wrap {
            display: flex;
            padding-left: 10px;

            i {
                font-size: 18px;
                margin-right: 5px;
            }

            .c-f-w-item {
                color: #2c3e50;
                span {
                    display: flex;
                    align-items: center;
                    justify-content: center;
                }
                &:hover {
                    color: #2680eb;
                }
            }
            .disabled {
                cursor: not-allowed;
                color: #ccc;
                &:hover {
                    color: #ccc;
                }
            }
        }
    }

    .canvas-tool {
        box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.12);
        border-radius: 14px;
        padding: 10px 5px;
        background: #fafafa;
        position: absolute;
        top: 35px;
        right: 0;
        z-index: 1;
        display: flex;
        align-items: center;
        justify-content: space-between;
        flex-direction: column;
        height: 200px;

        i {
            font-size: 18px;
            cursor: pointer;
            &:hover {
                color: #2680eb;
            }
        }
    }
}
</style>
